use crate::models::admins::{CreateAdminParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateAdminParams>,
) -> Result<Response> {
    let admin = Model::create_with_password(&ctx.db, &params).await?;
    format::json(admin)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let admin = Model::find_by_id(&ctx.db, &id).await?;
    format::json(admin)
}

#[debug_handler]
async fn find_by_email(
    State(ctx): State<AppContext>,
    Path(email): Path<String>,
) -> Result<Response> {
    let admin = Model::find_by_email(&ctx.db, &email).await?;
    format::json(admin)
}

#[debug_handler]
async fn update_password(
    State(ctx): State<AppContext>,
    Path(id): Path<String>,
    Json(password): Json<String>,
) -> Result<Response> {
    let admin = Model::find_by_id(&ctx.db, &id).await?;
    let admin = admin
        .into_active_model()
        .update_password(&ctx.db, &password)
        .await?;
    format::json(admin)
}

#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let admin = Model::find_by_id(&ctx.db, &id).await?;
    admin.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("admins")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/email/:email", get(find_by_email))
        .add("/:id/password", put(update_password))
        .add("/:id", delete(delete_by_id))
}
